<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { NButton, NInput, NPopover, NSpace, NCard, useMessage, NSpin } from 'naive-ui'
import { todoApi, type Todo } from '@/api/todo'

const message = useMessage()
const loading = ref(false)

// 获取待办列表
const { data: todosData, execute: rawFetchTodos } = todoApi.getTodos()

// 包装 fetchTodos，添加 loading 状态
const fetchTodos = async () => {
  loading.value = true
  try {
    await rawFetchTodos()
  } finally {
    loading.value = false
  }
}

const todos = computed<Todo[]>(() => {
  const result = todosData.value?.status === 'success' ? todosData.value.data : []
  console.log('待办列表:', result)
  return result
})

// 初始加载数据
onMounted(() => {
  fetchTodos()
})

const showAddPopover = ref(false)
const showEditPopover = ref(false)
const editingTodo = ref<Todo | null>(null)
const newTodo = ref({
  title: '',
  content: '',
})

// 添加待办事项
const handleAddTodo = async () => {
  if (!newTodo.value.title.trim()) {
    message.warning('请填写标题')
    return
  }

  loading.value = true
  try {
    const { data } = await todoApi.addTodo({
      title: newTodo.value.title,
      content: newTodo.value.content,
    })

    if (data.value?.status === 'success') {
      message.success('添加成功')
      newTodo.value = {
        title: '',
        content: '',
      }
      showAddPopover.value = false
      fetchTodos()
    } else {
      message.error(data.value?.message || '添加失败')
    }
  } finally {
    loading.value = false
  }
}

// 开始编辑
const startEdit = (todo: Todo) => {
  editingTodo.value = { ...todo }
  showEditPopover.value = true
}

// 保存编辑
const saveEdit = async () => {
  if (!editingTodo.value) return
  if (!editingTodo.value.title.trim()) {
    message.warning('请填写标题')
    return
  }

  loading.value = true
  try {
    const { data } = await todoApi.updateTodo({
      id: editingTodo.value._id,
      updates: {
        title: editingTodo.value.title,
        content: editingTodo.value.content,
        completed: editingTodo.value.completed,
      },
    })

    if (data.value?.status === 'success') {
      message.success('更新成功')
      showEditPopover.value = false
      editingTodo.value = null
      fetchTodos()
    } else {
      message.error(data.value?.message || '更新失败')
    }
  } finally {
    loading.value = false
  }
}

// 切换待办状态
const toggleTodo = async (todo: Todo) => {
  loading.value = true
  try {
    const { data } = await todoApi.updateTodo({
      id: todo._id,
      updates: {
        completed: !todo.completed,
      },
    })

    if (data.value?.status === 'success') {
      message.success(todo.completed ? '已取消完成' : '已完成')
      fetchTodos()
    } else {
      message.error(data.value?.message || '更新失败')
    }
  } finally {
    loading.value = false
  }
}

// 删除待办事项
const handleDeleteTodo = async (id: string) => {
  loading.value = true
  try {
    const { data } = await todoApi.deleteTodo(id)

    if (data.value?.status === 'success') {
      message.success('删除成功')
      fetchTodos()
    } else {
      message.error(data.value?.message || '删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleString()
}
</script>

<template>
  <NSpin :show="loading" description="加载中...">
    <div class="todo-container">
      <h2 class="text-2xl font-bold mb-6">待办事项</h2>

      <!-- 添加待办按钮 -->
      <div class="mb-6">
        <NPopover trigger="click" :show="showAddPopover" @update:show="showAddPopover = $event">
          <template #trigger>
            <NButton type="primary" @click="showAddPopover = true"> 添加待办 </NButton>
          </template>

          <!-- 添加待办表单 -->
          <div class="p-4 w-80">
            <NSpace vertical>
              <NInput
                v-model:value="newTodo.title"
                type="text"
                placeholder="输入标题"
                @keyup.enter="handleAddTodo"
              />
              <NInput
                v-model:value="newTodo.content"
                type="textarea"
                placeholder="输入内容（选填）"
                :autosize="{
                  minRows: 3,
                  maxRows: 5,
                }"
              />
              <div class="flex justify-end gap-2">
                <NButton @click="showAddPopover = false">取消</NButton>
                <NButton type="primary" @click="handleAddTodo">确定</NButton>
              </div>
            </NSpace>
          </div>
        </NPopover>
      </div>

      <!-- 编辑弹窗 -->
      <NPopover trigger="click" :show="showEditPopover" @update:show="showEditPopover = $event">
        <template #trigger>
          <div class="hidden">触发器</div>
        </template>
        <div class="p-4 w-80">
          <NSpace vertical>
            <NInput
              v-if="editingTodo"
              v-model:value="editingTodo.title"
              type="text"
              placeholder="输入标题"
            />
            <NInput
              v-if="editingTodo"
              v-model:value="editingTodo.content"
              type="textarea"
              placeholder="输入内容（选填）"
              :autosize="{
                minRows: 3,
                maxRows: 5,
              }"
            />
            <div class="flex justify-end gap-2">
              <NButton @click="showEditPopover = false">取消</NButton>
              <NButton type="primary" @click="saveEdit">保存</NButton>
            </div>
          </NSpace>
        </div>
      </NPopover>

      <!-- 待办列表 -->
      <div class="todo-list grid gap-4">
        <NCard v-for="todo in todos" :key="todo._id" class="todo-item">
          <template #header>
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                <input
                  type="checkbox"
                  :checked="todo.completed"
                  @change="toggleTodo(todo)"
                  class="w-4 h-4 text-primary rounded border-gray-300 focus:ring-primary"
                />
                <span :class="{ 'line-through text-gray-400': todo.completed }">
                  {{ todo.title }}
                </span>
              </div>
            </div>
          </template>
          <div class="space-y-2">
            <div class="text-sm">{{ todo.content }}</div>
            <div class="text-xs text-gray-400">
              <div>创建时间：{{ formatTime(todo.createTime) }}</div>
              <div v-if="todo.updateTime">修改时间：{{ formatTime(todo.updateTime) }}</div>
            </div>
            <div class="flex justify-end gap-2 mt-4">
              <NButton strong secondary type="info" @click="startEdit(todo)"> 编辑 </NButton>
              <NButton strong secondary type="error" @click="handleDeleteTodo(todo._id)">
                删除
              </NButton>
            </div>
          </div>
        </NCard>
      </div>

      <!-- 空状态 -->
      <div v-if="!todos.length" class="text-center text-gray-400 py-8">暂无待办事项</div>
    </div>
  </NSpin>
</template>

<style scoped>
.todo-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  min-height: 200px;
}

:deep(.n-spin-body) {
  width: 100%;
}

:deep(.n-spin-description) {
  font-size: 14px;
  margin-top: 8px;
}

.todo-list {
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.todo-item {
  transition: all 0.3s ease;
}

.todo-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>
